/*
 * three dimensional map
 * @author: HEX
 * @since: 2025-01-16
 * threeMap.vue
*/
<template>
  <!-- <div style="width: 100%; height: 94vh;"> -->
    <el-container style="width: 100%; height: 94vh;">
      <el-main padding="0">

        <div v-if="isHmaMessage" class="info-hma-message">
          <h3>监测站-45</h3>
          <img src="/images/水文监测站点.jpg" alt="">
          <p>位置：{{ siteInfo.location }}</p>
          <p>水质：{{ siteInfo.waterQuality }}</p>
          <p>水量：{{ siteInfo.waterQuantity }}</p>
          <p>水中污染物：{{ siteInfo.pollutantLevels }}</p>
          <p>微生物含量：{{ siteInfo.microbialContent }}</p>
          <a alt="点击跳转">点击查看详情</a>
            <div ref="chartRef" style="width: 100%; height: 300px;"></div>
        </div>
        <div id="cesiumContainer">
          <!-- 添加信息展示框 -->
          <div v-if="popupContent" class="info-popup" style="display: none;">
            <h3>{{ popupContent.title }}</h3>
            <p>{{ popupContent.description }}</p>
          </div>
          <!-- 距离测量弹窗 -->
          <div v-if="isDistanceMeasure" class="measure-tooltip" :style="measureTooltipStyle">
            {{ currentDistance }}
          </div>
          <!-- 面积测量弹窗 -->
          <div v-if="isAreaMeasure" class="measure-tooltip" :style="measureAreaTooltipStyle">
            {{ currentArea }}
          </div>
          <!-- 添加飞行路径对话框 -->
          <el-dialog v-model="flightDialogVisible" title="创建飞行路径">
            <el-form>
              <el-form-item label="路径名称">
                <el-input v-model="newFlightName" />
              </el-form-item>
              <el-form-item label="飞行高度">
                <el-input-number v-model="flightHeight" :min="100" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="flightDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmFlightPath">确认</el-button>
            </template>
          </el-dialog>

          <!-- 添加飞行控制弹窗 -->
          <div v-if="flightPaths.length > 0" class="flight-control">
            <el-table :data="flightPaths" border>
              <el-table-column prop="name" label="名称" align="center" width="90"/>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <div style="display: flex;">
                    <el-button @click="startFly(scope.row, scope.$index)">飞行</el-button>
                    <el-button @click="stopFly">暂停</el-button>
                    <el-button @click="continueFly">继续</el-button>
                    <el-button type="danger">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-main>
      <el-aside width="200px" style="background-color: #fff; padding-right: 0; border-right: none;">
        <el-row width="100%" :gutter="0">
          <el-col :span="24" style="flex: 1 " width="100 %">
            <h2 class="mb-2" style="color: black; font-size: large; font-weight: bold;">三维地图功能</h2>
            <el-menu default-active="2">
              <el-sub-menu index="1">
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>图层管理</span>
                </template>
                <el-menu-item-group title="影像底图">
                  <el-menu-item index=11 @click="handleOpen(11)">高德影像地图</el-menu-item>
                  <el-menu-item index=12 @click="handleOpen(12)">天地图影像地图</el-menu-item>
                </el-menu-item-group>
                <el-menu-item-group title="矢量底图">
                  <el-menu-item index=13 @click="handleOpen(13)">高德矢量地图</el-menu-item>
                  <el-menu-item index=14 @click="handleOpen(14)">天地图矢量地图</el-menu-item>
                </el-menu-item-group>
              </el-sub-menu>
              <el-sub-menu index="2">
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>地图工具栏</span>
                </template>
                <el-menu-item index=21 @click="handleOpen(21)">全屏切换</el-menu-item>
                <el-menu-item index=22 @click="handleOpen(22)">拉框放大</el-menu-item>
                <el-menu-item index=23 @click="handleOpen(23)">元素识别</el-menu-item>
                <el-menu-item index=24 @click="handleOpen(24)">平面切换</el-menu-item>
                <!-- <el-menu-item index="1-2" @click="handleOpen('1-2', ['2'])">漫游（已实现）</el-menu-item> -->
              </el-sub-menu>
              <el-sub-menu index="3">
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>多源数据</span>
                </template>
                <el-menu-item index=31 @click="handleOpen(31)">数字高程模型</el-menu-item>
                <el-menu-item index=32 @click="handleOpen(32)">数字正射影像</el-menu-item>
                <el-menu-item index=33 @click="handleOpen(33)">三维建筑模型</el-menu-item>
                <el-menu-item index=34 @click="handleOpen(34)">倾斜摄影模型</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="4">
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>场景控制</span>
                </template>
                <el-menu-item-group title="飞行路径编辑">
                  <el-menu-item index=411 @click="handleOpen(411)">{{!isPathEditing ? '路径编辑' : '停止编辑'}}</el-menu-item>
                  <el-menu-item index=412 @click="handleOpen(412)">参数配置</el-menu-item>
                </el-menu-item-group>
                <el-menu-item-group title="相机视角调整">
                  <el-sub-menu index=42 >
                    <template #title>视角模式</template>
                    <el-menu-item index=421 @click="isFirstPerson = true">第一人称视角</el-menu-item>
                    <el-menu-item index=422 @click="isFirstPerson = false">第三人称视角</el-menu-item>
                    <!-- <el-menu-item index=421 @click="handleOpen(421)">第一人称视角</el-menu-item>
                    <el-menu-item index=422 @click="handleOpen(422)">第三人称视角</el-menu-item> -->
                  </el-sub-menu>
                  <el-sub-menu index=43 >
                    <template #title>预设角度</template>
                    <el-menu-item index=431 @click="handleOpen(431)">45°俯视视角</el-menu-item>
                    <el-menu-item index=432 @click="handleOpen(432)">90°俯视视角</el-menu-item>
                  </el-sub-menu>
                </el-menu-item-group>
                <el-menu-item-group title="环境调整">
                  <el-sub-menu index=44 >
                    <template #title>天气条件</template>
                    <el-menu-item index=440 @click="clearWeatherEffects()">清除天气</el-menu-item>
                    <el-menu-item index=441 @click="handleOpen(441)">晴天</el-menu-item>
                    <el-menu-item index=442 @click="handleOpen(442)">雨天</el-menu-item>
                    <el-menu-item index=443 @click="handleOpen(443)">雾天</el-menu-item>
                    <el-menu-item index=444 @click="handleOpen(444)">雪天</el-menu-item>
                  </el-sub-menu>
                  <el-sub-menu index=45 >
                    <template #title>光照时间</template>
                    <el-menu-item index=451 @click="handleOpen(451)">日出时刻</el-menu-item>
                    <el-menu-item index=452 @click="handleOpen(452)">正午时刻</el-menu-item>
                    <el-menu-item index=453 @click="handleOpen(453)">黄昏时刻</el-menu-item>
                  </el-sub-menu>
                </el-menu-item-group>
              </el-sub-menu>
              <el-sub-menu index=5>
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>测量工具</span>
                </template>
                  <el-menu-item index="51" @click="handleOpen(51)">{{!isCoordinatePick ? '拾取坐标' : '停止测量'}}</el-menu-item>
                  <el-menu-item index="52" @click="handleOpen(52)">{{!isDistanceMeasure ? '距离测量' : '停止测量'}}</el-menu-item>
                  <el-menu-item index="53" @click="handleOpen(53)">{{!isAreaMeasure ? '面积测量' : '停止测量'}}</el-menu-item>
              </el-sub-menu>
            </el-menu>
          </el-col>
        </el-row>
      </el-aside>
    </el-container>
</template>

<script setup>
import * as Cesium from 'cesium';
import { Location } from '@element-plus/icons-vue';
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
// Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(125.998299, 48.559416, 126.52268, 48.846809);
const webKey = 'fdcd34a2141a47a01256b442617130f7'
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlOThlYzRkMC0zN2IwLTRkYzEtODU5Ny04YzI4NDYxMjRlYWYiLCJpZCI6MjY3MDk4LCJpYXQiOjE3MzYxNjkzMzd9.W0Lf2lL41lUoJ5B0n9vf43NlVUtDAAxdKaI692PlfpI';
// 天地图矢量底图
const tdtVecBasicLayer = new Cesium.WebMapTileServiceImageryProvider({
  // 天地图矢量地图服务的URL，包含获取瓦片所需的参数
  url:
    'http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=' +
    webKey,
  // 矢量地图的基础图层名称
  layer: 'tdtVecBasicLayer',
  // 地图样式设置为默认
  style: 'default',
  // 瓦片图片格式设置为JPEG
  format: 'image/jpeg',
  // 使用的瓦片矩阵集合ID，确保与Google Maps兼容
  tileMatrixSetID: 'GoogleMapsCompatible',
  // 初始状态下不显示该图层
  show: false,
})
// 天地图矢量注记底图
const tdtVecAnnoLayer = new Cesium.WebMapTileServiceImageryProvider({
  url:
    'http://t0.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=' +
    webKey,
  layer: 'tdtAnnoLayer',
  style: 'default',
  format: 'image/jpeg',
  tileMatrixSetID: 'GoogleMapsCompatible',
})
// 天地图影像底图
const tdtImgLayer = new Cesium.WebMapTileServiceImageryProvider({
  url:
    'http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=' +
    webKey,
  layer: 'tdtAnnoLayer',
  style: 'default',
  format: 'image/jpeg',
  tileMatrixSetID: 'GoogleMapsCompatible',
  show: false,
})
// 天地图影像注记底图
const tdtImgAnnoLayer = new Cesium.WebMapTileServiceImageryProvider({
  url:
    'http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=' +
    webKey,
  layer: 'tdtAnnoLayer',
  style: 'default',
  format: 'image/jpeg',
  tileMatrixSetID: 'GoogleMapsCompatible',
  show: false,
})
// 高德影像底图
const gaodeImgLayer = new Cesium.UrlTemplateImageryProvider({
  url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
  layer: 'gdVecBasicLayer',
  style: 'default',
  format: 'image/png',
  tileMatrixSetID: 'GoogleMapsCompatible',
  show: false,
})
// 高德矢量注记底图
const gaodeAnnoLayer = new Cesium.UrlTemplateImageryProvider({
  url: 'http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
  layer: 'gdAnnoLayer',
  style: 'default',
  format: 'image/jpeg',
  tileMatrixSetID: 'GoogleMapsCompatible',
})

const layer01 = ref(null);
const layer02 = ref(null);
const layer03 = ref(null);
const layer04 = ref(null);
const layer05 = ref(null);
const layer06 = ref(null);
let viewer;
let terrainProvider = new Cesium.CesiumTerrainProvider({
  // url:'http://localhost:9004/tile/terrain/V5lQ4Gls/layer.json?labtoken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiItMSxUaHUgQXByIDE4IDE1OjMwOjU3IENTVCAyMDI0In0.j_YKsCRsIQtpgOWfFvMwAP65Rlx9uXyVte_xkE95Vdo',
  url:'http://localhost:9004/terrain/V5lQ4Gls/',
});
let isFullscreen = false;
// 框选放大
const zoomTo = ref(false);
const coords = ref([]); // 存储坐标数据[起点, 终点]
let rectangleEntity = null; // 矩形实体
let handler = null; // 事件处理器
// 元素识别
const isIdentify = ref(false);
const popupContent = ref(null);
let pickHandler = null;
// 坐标测量
const isCoordinatePick = ref(false);
let coordinateHandler = null;
// 新增距离测量相关变量
const isDistanceMeasure = ref(false);
const currentLinePositions = ref([]);
const totalDistance = ref(0);
let distanceHandler = null;
let currentPolylineEntity = null;
let realTimePolylineEntity = null;
const measureTooltipStyle = ref({});
const currentDistance = ref('');
// 新增面积测量相关变量
const isAreaMeasure = ref(false);
const currentPolygonPositions = ref([]);
const totalArea = ref(0);
let areaHandler = null;
let currentPolygonEntity = null;
let realTimePolygonEntity = null;
const measureAreaTooltipStyle = ref({});
const currentArea = ref('');
// 新增飞行相关状态和变量
const isPathEditing = ref(false);
const flightPaths = ref([]); // 存储所有飞行路径
const currentPathPoints = ref([]); // 当前编辑的路径点
let pathEditHandler = null;
let pathEntities = []; // 存储路径点实体
const flightDialogVisible = ref(false);
const newFlightName = ref('');
const flightHeight = ref(1000);
const activeFlightIndex = ref(-1);
// let flightStartTime = null;
// let flightPauseTime = null;
const positionProperty = new Cesium.SampledPositionProperty();
let airplaneEntity = null;
const isFirstPerson = ref(false);
// 新增天气相关状态
const weatherStages = ref({
  fog: null,
  rain: null,
  snow: null,
  sunny: null
});
// 图表弹窗
const chartRef = ref(null);
const siteInfo = ref({
  name: '五大连池监测站点',
  location: '位置：五大连池景区莲花池北侧',
  waterQuality: '水质：Ⅱ类',
  waterQuantity: '水量：150m³',
  pollutantLevels: '水中污染物：总氮含量 0.2mg/L，总磷含量 0.03mg/L',
  microbialContent: '微生物含量：大肠杆菌 <10cfu/100ml，菌落总数 50cfu/ml'
});
let isHmaMessage = ref(false);
onMounted( () => {
  viewer = new Cesium.Viewer('cesiumContainer',{
        // 搜索框
        geocoder: false,
        // 动画控件
        animation: false,
        // 场景模式选择器,就是控制二三维的那个
        sceneModePicker: false,
        // 时间轴
        timeline: false,
        // 导航帮助提示按钮
        navigationHelpButton: false,
        // 全屏按钮
        fullscreenButton: false,
        // 地图选择器
        // baseLayerPicker: false
        // cesium 提供的官方地形
        terrain: Cesium.Terrain.fromWorldTerrain(),
        infoBox:false,
        selectionIndicator:false
  });
  // viewer.terrainProvider = terrainProvider;
  // viewer.scene.globe.terrainExaggeration = 3.0;
  // 默认视角
  viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(126.176868, 48.644028, 40000),
      orientation: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-75.0),
      }
  });
  
// 方式1：通过GeoJsonDataSource加载

  Cesium.GeoJsonDataSource.load('/geojson/StationsNull.geojson',{clampToGround:true,markerSymbol:"mountain"}).then((function(dataSource) {
    // viewer.dataSources.add(dataSource);

    // console.log(dataSource.entities.values);
    const entities = dataSource.entities.values;

    for(let i = 0; i < entities.length; i++){
      const entity = entities[i];
      entity.billboard = {
        image: '/locationWaterStations.png',
        // scale: 0.5,
        width: 40,
        height: 40,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      };
      viewer.entities.add(entity);
    }
  }
  ))

  destroyPickHandler();
  destroyZoomHandler();
  destroyCoordinateHandler();
  destroyDistanceHandler();
  destroyAreaHandler();
  clearWeatherEffects();
});
// #region 添加zoomTo工具函数
const initZoomHandler = () => {
  // handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  // 左键点击记录起点
  handler.setInputAction((movement) => {
    const position = viewer.camera.pickEllipsoid(movement.position);
    if (position) {
      coords.value[0] = Cesium.Cartographic.fromCartesian(position);
      console.log(coords.value[0]);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 鼠标移动绘制矩形
  handler.setInputAction((movement) => {
    if (!coords.value[0]) return;
    // 修正为 movement.position
    const position = viewer.camera.pickEllipsoid(movement.endPosition);
    if (position) {
      const currentPos = Cesium.Cartographic.fromCartesian(position);
      updateRectangle(coords.value[0], currentPos);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 右键点击完成框选
  handler.setInputAction((movement) => {
    const position = viewer.camera.pickEllipsoid(movement.position);
    if (position && coords.value[0]) {
      coords.value[1] = Cesium.Cartographic.fromCartesian(position);
      console.log(coords.value[1]);
      zoomToRectangle();
      clearDrawing();
    }
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

const updateRectangle = (start, end) => {
  // 直接使用起点和终点作为对角线顶点
  const rectangle = new Cesium.Rectangle(
    Math.min(start.longitude, end.longitude),
    Math.min(start.latitude, end.latitude),
    Math.max(start.longitude, end.longitude),
    Math.max(start.latitude, end.latitude)
  );
  console.log(rectangle);
  if (!rectangleEntity) {
    rectangleEntity = viewer.entities.add({
      rectangle: {
        coordinates: rectangle,
        material: Cesium.Color.WHITE.withAlpha(0.3), // 半透明填充
        // outline: true, // 显示边框
        // outlineColor: Cesium.Color.BLACK, // 边框颜色
        // outlineWidth: 2 // 边框宽度
      }
    });
  } else {
    rectangleEntity.rectangle.coordinates = rectangle;
    viewer.scene.requestRender(); // 强制重绘
  }
};

const zoomToRectangle = () => {
  const rectangle = Cesium.Rectangle.fromCartographicArray([
    new Cesium.Cartographic(coords.value[0].longitude, coords.value[1].latitude),
    new Cesium.Cartographic(coords.value[1].longitude, coords.value[0].latitude)
  ]);
  
  viewer.camera.flyTo({
    destination: Cesium.Rectangle.fromDegrees(
      Cesium.Math.toDegrees(rectangle.west),
      Cesium.Math.toDegrees(rectangle.south),
      Cesium.Math.toDegrees(rectangle.east),
      Cesium.Math.toDegrees(rectangle.north)
    )
  });
};

const clearDrawing = () => {
  if (rectangleEntity) {
    viewer.entities.remove(rectangleEntity);
    rectangleEntity = null;
  }
  coords.value = [];
};

const destroyZoomHandler = () => {
  handler?.destroy();
  handler = null;
  clearDrawing();
};
// #endregion

// #region 添加识别元素工具函数
// 初始化拾取处理器
const initPickHandler = () => {
  pickHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  pickHandler.setInputAction((click) => {
    const pickedObject = viewer.scene.pick(click.position);
    if (Cesium.defined(pickedObject)) {
      const entity = pickedObject.id;
      if (entity instanceof Cesium.Entity) {
        showPopup(
          entity.properties.name?.getValue(),
          entity.properties.description?.getValue(),
        );
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

// 销毁拾取处理器
const destroyPickHandler = () => {
  pickHandler?.destroy();
  pickHandler = null;
  popupContent.value = null;
};

// 显示弹窗
const showPopup = (title, description) => {

  popupContent.value = {
    title: title || "未命名对象",
    description: description || "暂无详细信息"
  };
  isHmaMessage = true;
  nextTick(() => {
      // echarts
  const chartDom = chartRef.value
  if (!chartDom) {
    console.error('Chart container not found.');
    return;
  }

  const myChart = echarts.init(chartDom);

  const option = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            label: {
                backgroundColor: '#6a7985'
            }
        }
    },
    toolbox: {},
    legend: {
        data: ['温度']
    },
    xAxis: [
        {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            data: ['7-1', '7-2', '7-3', '7-4', '7-5', '7-6', '7-7', '7-8', '7-9', '7-10', '7-11', '7-12']
        }
    ],
    yAxis: 
    {
        type: 'value',
        name: '水温 (°C)',
        position: 'left',
        axisLine: {
            show: true,
            lineStyle: {
                color: '##470C6' // 更改颜色为蓝色
            }
        },
        axisLabel: {
            formatter: '{value} ℃'
        }
    },
    series: [
        {
            name: '水温',
            type: 'line',
            smooth: true,
            itemStyle: {
                color: '#5470C6' // 更改线条颜色为红色
            },
            data: [12.0, 13.2, 12.3, 14.5, 16.3, 14.2, 12.3, 13.4, 13.0, 14.5, 12.0, 16.2]
        }
    ]
};

if (option && typeof option === 'object') {
    myChart.setOption(option);
}

  // 监听窗口大小变化，自动调整图表大小
  window.addEventListener('resize', () => {myChart.resize();});
  });
  // 3秒后自动关闭
  setTimeout(() => {
    popupContent.value = null;
    isHmaMessage = false;
  }, 5000);
};
// #endregion

// #region 添加坐标测量工具函数
// 初始化坐标拾取处理器
const initCoordinateHandler = () => {
  coordinateHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  coordinateHandler.setInputAction((click) => {
    const cartesian = viewer.camera.pickEllipsoid(click.position);
    if (cartesian) {
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
      
      showPopup(
        "坐标",
        `经度：${longitude}\n纬度：${latitude}`
      );
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

// 销毁坐标拾取处理器
const destroyCoordinateHandler = () => {
  coordinateHandler?.destroy();
  coordinateHandler = null;
  popupContent.value = null;
};
// #endregion

// #region 添加距离测量工具函数
// 初始化距离测量处理器
const initDistanceHandler = () => {
  // 重置状态
  currentLinePositions.value = [];
  totalDistance.value = 0;
  currentDistance.value = '';
  // 收集所有需要移除的实体
  const entitiesToRemove = [];
  viewer.entities.values.forEach(entity => {
    if (entity.point || entity.label || entity.polyline) {
      entitiesToRemove.push(entity);
    }
  });

  // 统一移除所有相关实体
  entitiesToRemove.forEach(entity => {
    viewer.entities.remove(entity);
  });

  // 重置实体引用
  currentPolylineEntity = null; // 重置当前折线实体
  realTimePolylineEntity = null; // 重置实时预览折线实体
  distanceHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

  // 左键点击添加点
  distanceHandler.setInputAction((click) => {
    const cartesian = viewer.scene.pickPosition(click.position);
    if (cartesian) {
      addMeasurementPoint(cartesian);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 鼠标移动更新提示
  distanceHandler.setInputAction((movement) => {
    const cartesian = viewer.scene.pickPosition(movement.endPosition);
    if (cartesian && currentLinePositions.value.length > 0) {
      updateMeasurementPreview(cartesian);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 右键结束测量
  distanceHandler.setInputAction(() => {
    if (currentLinePositions.value.length > 1) {
      addFinalLabel();
    }
    destroyDistanceHandler();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

// 添加测量点
const addMeasurementPoint = (position) => {
  // 添加点实体
  viewer.entities.add({
    position: position,
    point: {
      pixelSize: 8,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      color: Cesium.Color.YELLOW,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 2
    }
  });

  // 添加标签
  const labelText = currentLinePositions.value.length === 0 
    ? "起点" 
    : `${Cesium.Cartesian3.distance(
        currentLinePositions.value[currentLinePositions.value.length - 1],
        position
      ).toFixed(2)}米`;

  viewer.entities.add({
    position: position,
    label: {
      text: labelText,
      font: '14px sans-serif',
      fillColor: Cesium.Color.WHITE,
      backgroundColor: Cesium.Color.BLACK.withAlpha(0.7),
      backgroundPadding: new Cesium.Cartesian2(6, 4),
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      pixelOffset: new Cesium.Cartesian2(0, -20)
    }
  });

  // 更新线段
  if (currentLinePositions.value.length > 0) {
    const distance = Cesium.Cartesian3.distance(
      currentLinePositions.value[currentLinePositions.value.length - 1],
      position
    );
    totalDistance.value += distance;
  }

  currentLinePositions.value.push(position);
  updatePolyline();
};

// 更新预览线
const updateMeasurementPreview = (position) => {
  if (realTimePolylineEntity) {
    viewer.entities.remove(realTimePolylineEntity);
  }

  if (currentLinePositions.value.length > 0) {
    realTimePolylineEntity = viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(() => [
          ...currentLinePositions.value,
          position
        ], false),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        width: 3,
        material: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.CYAN
        })
      }
    });

    const distance = Cesium.Cartesian3.distance(
      currentLinePositions.value[currentLinePositions.value.length - 1],
      position
    );
    measureTooltipStyle.value = {
      left: `${event.clientX + 15}px`,
      top: `${event.clientY - 25}px`
    };
    currentDistance.value = `当前段: ${distance.toFixed(2)}米 | 总长: ${totalDistance.value.toFixed(2)}米`;
  }
};

// 更新实体折线
const updatePolyline = () => {
  if (currentPolylineEntity) {
    viewer.entities.remove(currentPolylineEntity);
  }

  currentPolylineEntity = viewer.entities.add({
    polyline: {
      positions: currentLinePositions.value,
      width: 4,
      material: Cesium.Color.YELLOW,
      arcType: Cesium.ArcType.GEODESIC
    }
  });
};

// 添加最终标签
const addFinalLabel = () => {
  if (currentLinePositions.value.length > 1) {
    const lastPosition = currentLinePositions.value[currentLinePositions.value.length - 1];
    viewer.entities.add({
      position: lastPosition,
      label: {
        text: `总长: ${totalDistance.value.toFixed(2)}米`,
        font: 'bold 14px sans-serif',
        fillColor: Cesium.Color.GOLD,
        backgroundColor: Cesium.Color.BLACK.withAlpha(0.7),
        pixelOffset: new Cesium.Cartesian2(0, -40)
      }
    });
  }
};

// 清理测量资源
const destroyDistanceHandler = () => {
  distanceHandler?.destroy();
  distanceHandler = null;
  
  // if (currentPolylineEntity) {
  //   viewer.entities.remove(currentPolylineEntity);
  //   currentPolylineEntity = null;
  // }
  
  if (realTimePolylineEntity) {
    viewer.entities.remove(realTimePolylineEntity);
    realTimePolylineEntity = null;
  }
  
  currentLinePositions.value = [];
  totalDistance.value = 0;
  currentDistance.value = '';
  isDistanceMeasure.value = false;
};
// #endregion

// #region 测量面积工具函数
// 初始化面积测量处理器
const initAreaHandler = () => {
  // 重置状态
  currentPolygonPositions.value = [];
  totalArea.value = 0;
  currentArea.value = '';
  
  // 清理旧实体
  const entitiesToRemove = [];
  viewer.entities.values.forEach(entity => {
    if (entity.polygon || entity.point || entity.label) {
      entitiesToRemove.push(entity);
    }
  });
  entitiesToRemove.forEach(entity => viewer.entities.remove(entity));

  areaHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

  // 左键点击添加点
  areaHandler.setInputAction((click) => {
    const cartesian = viewer.scene.pickPosition(click.position);
    if (cartesian) {
      addPolygonPoint(cartesian);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 鼠标移动更新提示
  areaHandler.setInputAction((movement) => {
    const cartesian = viewer.scene.pickPosition(movement.endPosition);
    if (cartesian && currentPolygonPositions.value.length > 0) {
      updatePolygonPreview(cartesian);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 右键结束测量
  areaHandler.setInputAction(() => {
    if (currentPolygonPositions.value.length > 2) {
      finalizePolygon();
    }
    destroyAreaHandler();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

// 添加多边形点
const addPolygonPoint = (position) => {
  // 添加点实体
  viewer.entities.add({
    position: position,
    point: {
      pixelSize: 8,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND  + 100,
      color: Cesium.Color.BLUE,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2
    }
  });

  // 添加顺序标签
  viewer.entities.add({
    position: position,
    label: {
      text: `${currentPolygonPositions.value.length + 1}`,
      font: '14px sans-serif',
      fillColor: Cesium.Color.WHITE,
      backgroundColor: Cesium.Color.BLUE.withAlpha(0.7),
      backgroundPadding: new Cesium.Cartesian2(6, 4),
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      pixelOffset: new Cesium.Cartesian2(0, -20)
    }
  });

  currentPolygonPositions.value.push(position);
  updatePolygon();
};

// 更新预览多边形
const updatePolygonPreview = (position) => {
  if (realTimePolygonEntity) {
    viewer.entities.remove(realTimePolygonEntity);
  }

  if (currentPolygonPositions.value.length > 1) {
    realTimePolygonEntity = viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(() => 
          new Cesium.PolygonHierarchy([...currentPolygonPositions.value, position]), false),
        material: Cesium.Color.BLUE.withAlpha(0.3),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      }
    });

    // 计算实时面积
    const tempPositions = [...currentPolygonPositions.value, position];
    const area = calculateArea(tempPositions);
    measureAreaTooltipStyle.value = {
      left: `${event.clientX + 15}px`,
      top: `${event.clientY - 25}px`
    };
    currentArea.value = `实时面积: ${(area / 1000000).toFixed(2)} 公顷`;
  }
};

// 更新实体多边形
const updatePolygon = () => {
  if (currentPolygonEntity) {
    viewer.entities.remove(currentPolygonEntity);
  }

  if (currentPolygonPositions.value.length > 2) {
    currentPolygonEntity = viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(() => 
          new Cesium.PolygonHierarchy(currentPolygonPositions.value), false),
        material: Cesium.Color.BLUE.withAlpha(0.3),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
      }
    });
  }
};

// 计算多边形面积
const calculateArea = (positions) => {
  if (positions.length < 3) return 0;
  // const polygon = new Cesium.PolygonGeometry({
  //   polygonHierarchy: new Cesium.PolygonHierarchy(positions),
  //   height: 0,
  //   vertexFormat: Cesium.VertexFormat.POSITION_ONLY
  // });
  let area = 0;
  for(let i = 0; i < positions.length; i++){
    console.log(positions[i]);
    area +=  positions[i].y;
  }
  console.log(area);
  return area*100;
  // 13612721.149447978 10000000000
  // const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
  // return Cesium.Geometry.computeArea(geometry);
};

// 完成多边形测量
const finalizePolygon = () => {
  const area = calculateArea(currentPolygonPositions.value);
  totalArea.value = area;
  
  // 添加中心点标签
  const center = Cesium.BoundingSphere.fromPoints(currentPolygonPositions.value).center;
  viewer.entities.add({
    position: center,
    label: {
      text: `总面积: ${(area / 1000000).toFixed(2)} 公顷`,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      font: 'bold 14px sans-serif',
      fillColor: Cesium.Color.WHITE,
      backgroundColor: Cesium.Color.BLUE.withAlpha(0.7),
      pixelOffset: new Cesium.Cartesian2(0, -40)
    }
  });
  // 使用currentPolygonPositions数组点创建一个面
  viewer.entities.add({
    polygon: {
      hierarchy: new Cesium.PolygonHierarchy(currentPolygonPositions.value),
      material: Cesium.Color.BLUE.withAlpha(0.3),
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
    }
  });
  for(let i = 0; i < currentPolygonPositions.value.length; i++){
    console.log(currentPolygonPositions.value[i]);
  }
};

// 清理测量资源
const destroyAreaHandler = () => {
  areaHandler?.destroy();
  areaHandler = null;
  
  if (realTimePolygonEntity) {
    viewer.entities.remove(realTimePolygonEntity);
    realTimePolygonEntity = null;
  }
  
  currentPolygonPositions.value = [];
  totalArea.value = 0;
  currentArea.value = '';
  isAreaMeasure.value = false;
};

// #endregion

// #region  自定义飞行工具函数
// 初始化路径编辑处理器
const initPathEditHandler = () => {
  clearPathEntities();
  currentPathPoints.value = [];
  
  pathEditHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  
  // 左键添加点
  pathEditHandler.setInputAction(click => {
    const cartesian = viewer.scene.pickPosition(click.position);
    if (cartesian) {
      addPathPoint(cartesian);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 右键结束编辑
  pathEditHandler.setInputAction(() => {
    if (currentPathPoints.value.length > 0) {
      flightDialogVisible.value = true;
    }
    // destroyPathEditHandler();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

// 添加路径点
const addPathPoint = (position) => {
  const index = currentPathPoints.value.length + 1;
  
  // 添加点实体
  const pointEntity = viewer.entities.add({
    position: position,
    point: {
      pixelSize: 10,
      color: Cesium.Color.RED,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2
    }
  });

  // 添加标签
  const labelEntity = viewer.entities.add({
    position: position,
    label: {
      text: `节点${index}`,
      font: '14px sans-serif',
      fillColor: Cesium.Color.WHITE,
      backgroundColor: Cesium.Color.BLACK.withAlpha(0.7),
      pixelOffset: new Cesium.Cartesian2(0, -20)
    }
  });

  pathEntities.push(pointEntity, labelEntity);
  currentPathPoints.value.push(position);
};

// 清除路径实体
const clearPathEntities = () => {
  pathEntities.forEach(entity => viewer.entities.remove(entity));
  pathEntities = [];
};

// 销毁路径编辑处理器
const destroyPathEditHandler = () => {
  pathEditHandler?.destroy();
  pathEditHandler = null;
  isPathEditing.value = false;
  clearPathEntities()
  flightPaths.value = [];
};

// 确认创建飞行路径
const confirmFlightPath = () => {
  if (newFlightName.value && currentPathPoints.value.length > 0) {
    flightPaths.value.push({
      name: newFlightName.value,
      height: flightHeight.value,
      points: [...currentPathPoints.value]
    });
    flightDialogVisible.value = false;
    newFlightName.value = '';
    flightHeight.value = 1000;
  }
};

// 生成飞行路径
const generateFlightPath = (points, height) => {
  const property = new Cesium.SampledPositionProperty();
  const start = Cesium.JulianDate.now();
  
  points.forEach((point, index) => {
    const time = Cesium.JulianDate.addSeconds(
      start,
      index * 10, // 每点间隔10秒
      new Cesium.JulianDate()
    );
    
    const position = Cesium.Cartesian3.clone(point);
    position.z += height; // 应用飞行高度
    
    property.addSample(time, position);
  });

  return property;
};

// 开始飞行
const startFly = (row, index) => {
  activeFlightIndex.value = index;
  const path = flightPaths.value[index];
  
  // 清除之前的飞机实体
  if (airplaneEntity) {
    viewer.entities.remove(airplaneEntity);
  }

  // 创建时间轴
  const start = Cesium.JulianDate.now();
  const timeStep = 10; // 每个点间隔10秒
  const totalSeconds = (path.points.length - 1) * timeStep;
  const stop = Cesium.JulianDate.addSeconds(start, totalSeconds, new Cesium.JulianDate());

  // 配置时钟参数
  viewer.clock.startTime = start.clone();
  viewer.clock.stopTime = stop.clone();
  viewer.clock.currentTime = start.clone();
  viewer.clock.multiplier = 1; // 播放速度

  // 构建采样位置属性
  path.points.forEach((point, i) => {
    const time = Cesium.JulianDate.addSeconds(
      start,
      i * timeStep,
      new Cesium.JulianDate()
    );
    
    // 创建带高度的三维坐标
    const position = Cesium.Cartesian3.fromDegrees(
      Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(point).longitude),
      Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(point).latitude),
      path.height
    );
    
    positionProperty.addSample(time, position);
  });

  // 创建飞机模型实体
  airplaneEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({ start, stop })
    ]),
    position: positionProperty,
    model: {
      uri: '/Cesium_Air.glb', // 替换为实际模型路径
      // minimumPixelSize: 128,
      scale: isFirstPerson.value ? 0.0 : 0.5
    },
    orientation: new Cesium.VelocityOrientationProperty(positionProperty),
    path: new Cesium.PathGraphics({
      width: 3,
      material: new Cesium.PolylineGlowMaterialProperty({
        glowPower: 0.2,
        color: Cesium.Color.YELLOW
      })
    })
  });
  console.log(isFirstPerson.value);
  // 设置相机跟踪
  viewer.trackedEntity = airplaneEntity;
  // 设置相机俯视角度为45度
  viewer.camera.setView({
    orientation: {
      heading: Cesium.Math.toRadians(0), // 方向角（0为北）
      pitch: Cesium.Math.toRadians(-90), // 俯仰角（负值表示向下）
      roll: 0 // 翻滚角
    }
  });
  // 启动动画
  viewer.clock.shouldAnimate = true;
};

// 修改暂停/继续函数
const stopFly = () => {
  viewer.clock.shouldAnimate = false;
};

const continueFly = () => {
  viewer.clock.shouldAnimate = true;
};

// #endregion

// #region  天气着色器
// 定义天气着色器代码
const weatherShaders = {
  fog: `
    uniform sampler2D colorTexture;
    uniform sampler2D depthTexture;
    uniform float visibility;
    uniform vec4 fogColor;
    in vec2 v_textureCoordinates;
    out vec4 fragColor; // 定义输出变量

    void main(void) 
    { 
      vec4 origcolor = texture(colorTexture, v_textureCoordinates); // 使用 texture 替代 texture2D
      float v = gl_FragCoord.y / czm_viewport.w;
      float f = v * visibility;
      fragColor = mix(origcolor, fogColor, f); // 使用 fragColor 替代 gl_FragColor
    }`,

  rain: `
    uniform sampler2D colorTexture;
    in vec2 v_textureCoordinates;
    out vec4 fragColor; // 定义输出变量

    float hash(float x) {
      return fract(sin(x * 133.3) * 13.13);
    }

    void main(void) {
      float time = czm_frameNumber / 100.0;
      vec2 resolution = czm_viewport.zw;
      vec2 uv = (gl_FragCoord.xy * 2.0 - resolution.xy) / min(resolution.x, resolution.y);
      vec3 c = vec3(0.6, 0.7, 0.8);
      float a = -0.4;
      float si = sin(a), co = cos(a);
      uv *= mat2(co, -si, si, co);
      uv *= length(uv + vec2(0, 4.9)) * 0.3 + 1.0;
      float v = 1.0 - sin(hash(floor(uv.x * 100.0)) * 2.0);
      float b = clamp(abs(sin(10.0 * time * v + uv.y * (5.0 / (2.0 + v))) - 0.95), 0.0, 1.0) * 1.0;
      c *= v * b; // 屏幕上雨的颜色
      fragColor = mix(texture(colorTexture, v_textureCoordinates), vec4(c, 1.0), 0.2); // 使用 texture 和 fragColor
    }`,

  snow: `
    uniform sampler2D colorTexture; 
    in vec2 v_textureCoordinates;
    uniform vec4 fogColor;
    out vec4 fragColor; // 定义输出变量

    float snow(vec2 uv, float scale) {
      float time = czm_frameNumber / 60.0;
      float w = smoothstep(1.0, 0.0, -uv.y * (scale / 10.0));
      if (w < 0.1) return 0.0;
      uv += time / scale;
      uv.y += time * 2.0 / scale;
      uv.x += sin(uv.y + time * 0.5) / scale;
      uv *= scale;
      vec2 s = floor(uv), f = fract(uv), p;
      float k = 3.0, d;
      p = 0.5 + 0.35 * sin(11.0 * fract(sin((s + p + scale) * mat2(7, 3, 6, 5)) * 5.0)) - f;
      d = length(p);
      k = min(d, k);
      k = smoothstep(0.0, k, sin(f.x + f.y) * 0.01);
      return k * w;
    }

    void main(void) {
      vec2 resolution = czm_viewport.zw;
      vec2 uv = (gl_FragCoord.xy * 2.0 - resolution.xy) / min(resolution.x, resolution.y);
      vec3 finalColor = vec3(0.0);
      float c = 0.0;
      c += snow(uv, 30.0) * 0.0;
      c += snow(uv, 20.0) * 0.0;
      c += snow(uv, 15.0) * 0.0;
      c += snow(uv, 10.0);
      c += snow(uv, 8.0);
      c += snow(uv, 6.0);
      c += snow(uv, 5.0);
      finalColor = vec3(c); // 屏幕上雪的颜色

      if (c <= 0.2) {
        fragColor = mix(texture(colorTexture, v_textureCoordinates), vec4(1.0, 1.0, 1.0, 1.0), 0.0); // 使用 texture 和 fragColor
      } else {
        fragColor = mix(texture(colorTexture, v_textureCoordinates), fogColor, 1.0); // 使用 texture 和 fragColor
      }
    }`,

  sunny: `
    uniform sampler2D colorTexture;
    uniform sampler2D depthTexture;
    uniform float visibility;
    uniform vec4 fogColor;
    in vec2 v_textureCoordinates;
    out vec4 fragColor; // 定义输出变量

    void main(void) 
    { 
      vec4 origcolor = texture(colorTexture, v_textureCoordinates); // 使用 texture 替代 texture2D
      float y = gl_FragCoord.y / czm_viewport.w;
      float x = gl_FragCoord.x / czm_viewport.z;
      float f = (1.0 - x) * y;
      fragColor = mix(origcolor, fogColor, f); // 使用 fragColor 替代 gl_FragColor
    }`
};

// 创建天气效果
const createWeatherStage = (type) => {
  // if (weatherStages.value[type]) {
  //   viewer.scene.postProcessStages.remove(weatherStages.value[type]);
  //   console.log("移除成功"+ weatherStages.value[type]);
  // }
  if (weatherStages.value[type]) return;

  weatherStages.value[type] = new Cesium.PostProcessStage({
    name: `czm_${type}`,
    fragmentShader: weatherShaders[type],
    uniforms: {
      visibility: () => 0.7,
      fogColor: () => new Cesium.Color(0.8, 0.8, 0.8, 0.5)
    }
  });
};

// 清除所有天气效果
const clearWeatherEffects = () => {
  Object.keys(weatherStages.value).forEach(key => {
    const stage = weatherStages.value[key];
    if (stage) {
      // 移除 PostProcessStage
      viewer.scene.postProcessStages.remove(stage);
      // 确保 weatherStages.value 正确更新
      weatherStages.value[key] = null;
    }
  });
};

// 新增光照控制相关状态
const lightingConditions = {
  sunrise: {
    color: new Cesium.Color(1.0, 0.8, 0.6, 1.0), // 暖黄色
    intensity: 0.7,
    direction: new Cesium.Cartesian3(0.5, 0.5, 1.0)
  },
  noon: {
    color: Cesium.Color.WHITE, // 白光
    intensity: 1.0,
    direction: new Cesium.Cartesian3(0.0, 0.0, 1.0)
  },
  dusk: {
    color: new Cesium.Color(1.0, 0.6, 0.4, 1.0), // 橙红色
    intensity: 0.5,
    direction: new Cesium.Cartesian3(-0.5, -0.5, 1.0)
  }
};

// 设置光照效果
const setLightingCondition = (condition) => {
  const config = lightingConditions[condition];
  
  // 设置光照参数
  viewer.scene.light = new Cesium.DirectionalLight({
    direction: config.direction,
    color: config.color,
    intensity: config.intensity
  });

  // 调整全局光照参数
  viewer.scene.globe.enableLighting = true;
  viewer.scene.globe.dynamicAtmosphereLighting = true;
  viewer.scene.globe.dynamicAtmosphereLightingFromSun = false;
  
  // 调整阴影参数（可选）
  viewer.shadows = true;
  viewer.shadowMap.soft = true;
  viewer.shadowMap.darkness = 0.5;
};
// 添加动态时间变化（可选）
const setDynamicTime = (hour) => {
  const now = new Date();
  now.setHours(hour);
  now.setMinutes(0);
  viewer.clock.currentTime = Cesium.JulianDate.fromDate(now);
  viewer.scene.light = viewer.scene.sunLight; // 使用自然光照
};

// #endregion

const handleOpen = (key) => {
  switch (key) {
    case 11:
      layer01.value.show = !layer01.value.show;
      break;
    case 12:
      layer02.value.show = !layer02.value.show;
      layer03.value.show = !layer03.value.show;
      break;
    case 13:
      layer04.value.show = !layer04.value.show;
      break;
    case 14:
      layer05.value.show = !layer05.value.show;
      layer06.value.show = !layer06.value.show;
      break;
    case 21:
      if (!isFullscreen) {
        Cesium.Fullscreen.requestFullscreen(document.body)
      } else {
        Cesium.Fullscreen.exitFullscreen();
      }
      isFullscreen = !isFullscreen;
      break;
    case 22:
      zoomTo.value = !zoomTo.value;
      if (zoomTo.value) {
        initZoomHandler();
        console.log('zoomTo.value is true')
      } else {
        destroyZoomHandler();
        console.log('zoomTo.value is false')
      }
      break;
    case 23:
      isIdentify.value = !isIdentify.value;
        if (isIdentify.value) {
          initPickHandler();
        } else {
          destroyPickHandler();
        }
        break;
    case 51:
      isCoordinatePick.value = !isCoordinatePick.value;
        if (isCoordinatePick.value) {
          initCoordinateHandler();
          console.log('isCoordinatePick.value is true')
        } else {
          destroyCoordinateHandler();
          console.log('isCoordinatePick.value is false')
        }
        break;
    case 52:
      isDistanceMeasure.value = !isDistanceMeasure.value;
        if (isDistanceMeasure.value) {
          initDistanceHandler();
        } else {
          destroyDistanceHandler();
        }
        break;
    case 53:
      isAreaMeasure.value = !isAreaMeasure.value;
      if (isAreaMeasure.value) {
        initAreaHandler();
      } else {
        destroyAreaHandler();
      }
      break;
    case 411:
      isPathEditing.value = !isPathEditing.value;
      if (isPathEditing.value) {
        initPathEditHandler();
      } else {
        destroyPathEditHandler();
      }
      break;
    case 441: // 晴天
      clearWeatherEffects();
      createWeatherStage('sunny');
      viewer.scene.postProcessStages.add(weatherStages.value.sunny);
      break;

    case 442: // 雨天
      clearWeatherEffects();
      createWeatherStage('rain');
      viewer.scene.postProcessStages.add(weatherStages.value.rain);
      break;

    case 443: // 雾天
      clearWeatherEffects();
      createWeatherStage('fog');
      viewer.scene.postProcessStages.add(weatherStages.value.fog);
      break;

    // 可选添加雪天效果
    case 444: 
      clearWeatherEffects();
      createWeatherStage('snow');
      viewer.scene.postProcessStages.add(weatherStages.value.snow);
      break;

    case 451: // 日出
      setLightingCondition('sunrise');
      setDynamicTime(6); // 设置为早上6点
      break;
    case 452: // 正午
      setLightingCondition('noon');
      setDynamicTime(12); // 设置为中午12点
      break;
    case 453: // 黄昏
      setLightingCondition('dusk');
      setDynamicTime(18); // 设置为下午6点
      break;
  }
  // console.log(key, keyPath)
}
// const handleClose = (key, keyPath) => {
//   console.log(key, keyPath)
// }
// onUnmounted(() => {
//   destroyPickHandler();
//   destroyZoomHandler();
//   destroyCoordinateHandler();
//   destroyDistanceHandler();
//   destroyAreaHandler();
//   clearWeatherEffects();
// });
</script>

<style scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
/* 隐藏底部cesium icon */
:deep(.cesium-viewer-bottom) {
    display: none !important;
}
.el-container .el-main {
  padding: 0;
}
.el-container .el-aside{
  background-color: rgb(20, 20, 20);
}
/* 新增识别信息弹窗样式 */
.info-popup {
  position: fixed;  /* 改为固定定位 */
  top: 20%;         /* 垂直居中起点 */
  right: 250px;
  transform: translateY(-50%); /* 垂直居中偏移 */
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  /* color: #fff; */
  padding: 15px;
  border-radius: 5px;
  max-width: 300px;
  z-index: 999;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 添加阴影增强层次感 */
}

/* 保持原有文字样式不变 */
.info-popup h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #409eff;
}

.info-popup p {
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-line; /* 新增换行样式 */
}
/* 添加测量提示样式 */
.measure-tooltip {
  position: fixed;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  pointer-events: none;
  z-index: 1000;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
/* 添加自定义飞行提示样式 */
.flight-control {
  position: fixed;
  top: 15%;
  right: 220px;
  width: 400px;
  background: rgba(255, 255, 255, 0.9);
  padding: 5px;
  border-radius: 5px;
  z-index: 999;
}
/* 气象信息弹窗样式 */
.info-hma-message{
  position: fixed;
  top: 40%;
  left: 160px;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  z-index: 999;
  margin: 50px;
  padding: 20px;
  border-radius: 20px;
}
.info-hma-message h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.info-hma-message p {
  margin: 0;
  font-size: 14px;
  font-weight: bold;
  line-height: 1.5;
  white-space: pre-line; /* 新增换行样式 */
}
.info-hma-message img{
  height: 200px;
  width: 400px;
}
.info-hma-message a{
  color: skyblue;
}

</style>